//
//  PoisonPlayVC.swift
//  Game
//
//  Created by woniu on 2025/9/25.
//毒药游戏，卡片中包含两个随机毒药。

import Foundation
import UIKit
import SnapKit

class PoisonPlayVC: BaseVC {
    
    public var gameModel:GameModel!
    //数据源，单词列表
    private var wordSets: Set<String> = []
    
    // 游戏模型
    private var poisonGameModel: PoisonGameModel!
    
    // 毒药槽位视图
    private var poisonSlotOne: PoisonSlotView!
    private var poisonSlotTwo: PoisonSlotView!
    
    // 按钮
    private var startButton: UIButton!
    private var resetButton: UIButton!
    
    // 卡片集合视图
    private var cardCollectionView: UICollectionView!
    
    // 当前卡片单词列表
    private var currentWords: [String] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupGame()
    }
    
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        
        // 屏幕旋转时重新布局卡片
        coordinator.animate(alongsideTransition: { _ in
            self.updateCollectionViewLayout()
        }, completion: nil)
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        // 确保在视图布局完成后再更新布局
        updateCollectionViewLayout()
    }
    
    private func setupGame() {
        // 初始化游戏模型
        poisonGameModel = PoisonGameModel()
        
        // 初始化测试数据
        setupTestData()
        
        // 创建UI
        createUI()
        
        // 初始化卡片
        setupCards()
    }
    
    private func setupTestData() {
        // 添加一些测试数据
        let dic = gameModel.jsonData.toDic()
        let configModel = FindeWordConfig.deserialize(from: dic) ?? FindeWordConfig()
        self.wordSets = Set(configModel.inputContentList)
    }
    
    private func createUI() {
        // 创建毒药槽位
        poisonSlotOne = PoisonSlotView()
        poisonSlotOne.title = "毒药一"
        view.addSubview(poisonSlotOne)
        
        poisonSlotTwo = PoisonSlotView()
        poisonSlotTwo.title = "毒药二"
        view.addSubview(poisonSlotTwo)
        
        // 创建按钮
        startButton = UIButton(type: .system)
        startButton.setTitle("开始", for: .normal)
        startButton.setTitleColor(.white, for: .normal)
        startButton.backgroundColor = UIColor.systemBlue
        startButton.layer.cornerRadius = 8
        startButton.addTarget(self, action: #selector(startGame), for: .touchUpInside)
        view.addSubview(startButton)
        
        resetButton = UIButton(type: .system)
        resetButton.setTitle("重置", for: .normal)
        resetButton.setTitleColor(.white, for: .normal)
        resetButton.backgroundColor = UIColor.systemGray
        resetButton.layer.cornerRadius = 8
        resetButton.addTarget(self, action: #selector(resetGame), for: .touchUpInside)
        view.addSubview(resetButton)
        
        // 创建卡片集合视图
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumInteritemSpacing = 10
        layout.minimumLineSpacing = 10
        
        cardCollectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cardCollectionView.backgroundColor = .clear
        cardCollectionView.showsVerticalScrollIndicator = true
        cardCollectionView.delegate = self
        cardCollectionView.dataSource = self
        cardCollectionView.register(PoisonCollectionViewCell.self, forCellWithReuseIdentifier: "PoisonCardCell")
        view.addSubview(cardCollectionView)
        
        // 设置约束
        poisonSlotTwo.snp.makeConstraints { make in
            make.centerY.equalTo(backButton.snp.centerY).offset(10)
            make.right.equalToSuperview().offset(-20)
            make.width.equalTo(80)
            make.height.equalTo(40)
        }
        
        poisonSlotOne.snp.makeConstraints { make in
            make.centerY.equalTo(poisonSlotTwo.snp.centerY)
            make.right.equalTo(poisonSlotTwo.snp.left).offset(-15)
            make.width.equalTo(80)
            make.height.equalTo(40)
        }
        //重置
        resetButton.snp.makeConstraints { make in
            make.right.equalTo(poisonSlotOne.snp.left).offset(-20)
            make.centerY.equalTo(poisonSlotTwo.snp.centerY)
            make.width.equalTo(100)
            make.height.equalTo(40)
        }
        //开始
        startButton.snp.makeConstraints { make in
            make.right.equalTo(resetButton.snp.left).offset(-15)
            make.centerY.equalTo(poisonSlotTwo.snp.centerY)
            make.width.equalTo(100)
            make.height.equalTo(40)
        }
        
        cardCollectionView.snp.makeConstraints { make in
            make.top.equalTo(poisonSlotTwo.snp.bottom)
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.bottom.equalToSuperview()
        }
    }
    
    private func setupCards() {
        // 获取单词列表并打乱顺序
        var words = Array(wordSets)
        words.shuffle()
        
        // 更新当前单词列表
        currentWords = words
        
        // 更新集合视图
        cardCollectionView.reloadData()
    }
    
    private func updateCollectionViewLayout() {
        guard let layout = cardCollectionView.collectionViewLayout as? UICollectionViewFlowLayout else { return }
        
        // 确保在有有效bounds的情况下才更新布局
        guard cardCollectionView.bounds.width > 0 else { return }
        
        // 根据屏幕方向确定每行卡片数
        let cols = getColumnsForCurrentOrientation()
        let spacing: CGFloat = 10
        
        // 计算卡片宽度
        let collectionViewWidth = cardCollectionView.bounds.width
        let cardWidth = (collectionViewWidth - CGFloat(cols + 1) * spacing) / CGFloat(cols)
        
        // 设置卡片尺寸
        layout.itemSize = CGSize(width: cardWidth, height: cardWidth * 6 / 9)
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        layout.minimumInteritemSpacing = 10
        layout.minimumLineSpacing = 10
    }
    
    // 根据屏幕方向获取每行卡片数
    private func getColumnsForCurrentOrientation() -> Int {
        let screenSize = UIScreen.main.bounds.size
        let isLandscape = screenSize.width > screenSize.height
        return isLandscape ? 6 : 4
    }
    
    @objc private func startGame() {
        guard !poisonGameModel.gameStarted else { return }
        
        // 随机选择两个毒药单词
        var poisonWords: Set<String> = []
        var availableIndices: [Int] = Array(0..<currentWords.count)
        availableIndices.shuffle()
        
        // 确保至少有两个单词
        guard availableIndices.count >= 2 else { return }
        
        let poisonIndex1 = availableIndices[0]
        let poisonIndex2 = availableIndices[1]
        
        poisonWords.insert(currentWords[poisonIndex1])
        poisonWords.insert(currentWords[poisonIndex2])
        
        // 设置毒药单词
        poisonGameModel.setPoisonWords(poisonWords)
        
        // 执行毒药卡片动画
        let cell1 = cardCollectionView.cellForItem(at: IndexPath(item: poisonIndex1, section: 0)) as? PoisonCollectionViewCell
        let cell2 = cardCollectionView.cellForItem(at: IndexPath(item: poisonIndex2, section: 0)) as? PoisonCollectionViewCell
        
        if let cell1 = cell1, let cell2 = cell2 {
            poisonSlotOne.setPoisonCard(with: currentWords[poisonIndex1], from: cell1.cardView, sourceSuperview: view)
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                self.poisonSlotTwo.setPoisonCard(with: self.currentWords[poisonIndex2], from: cell2.cardView, sourceSuperview: self.view)
            }
        }
        
        // 延迟重置卡片网格
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            self.resetCards()
        }
    }
    
    @objc private func resetGame() {
        // 重置游戏模型
        poisonGameModel.reset()
        
        // 重置槽位
        poisonSlotOne.resetSlot()
        poisonSlotTwo.resetSlot()
        
        // 重置卡片
        resetCards()
    }
    
    private func resetCards() {
        // 重新排列卡片
        setupCards()
    }
}

// MARK: - UICollectionViewDataSource & UICollectionViewDelegate
extension PoisonPlayVC: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return currentWords.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PoisonCardCell", for: indexPath) as! PoisonCollectionViewCell
        cell.configure(with: currentWords[indexPath.item])
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard poisonGameModel.gameStarted else { return } // 游戏未开始不能翻牌
        
        let cell = collectionView.cellForItem(at: indexPath) as? PoisonCollectionViewCell
        guard let cell = cell else { return }
        guard !cell.cardView.isFlipped else { return } // 已翻过的牌不能再翻
        
        // 翻转卡片
        cell.cardView.flipCard { [weak self] in
            guard let self = self else { return }
            
            // 检查是否为毒药卡片
            if self.poisonGameModel.isPoisonWord(cell.cardView.word) {
                cell.cardView.isPoison = true
                Utils.playErrorSound()
                // 显示游戏结束提示
                let alert = UIAlertController(title: "游戏结束", message: "你翻到了毒药卡片！", preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "确定", style: .default, handler: nil))
                self.present(alert, animated: true, completion: nil)
            }
        }
    }
}
